import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useChatStore = defineStore('chat', () => {
  // 生成或获取 memoryId
  const getMemoryId = () => {
    const stored = localStorage.getItem('memoryId')
    if (stored) {
      return parseInt(stored)
    }
    const newId = Math.floor(Math.random() * 1000000) + 1
    localStorage.setItem('memoryId', newId.toString())
    return newId
  }

  const memoryId = ref(getMemoryId())
  const messages = ref([])
  const isLoading = ref(false)

  // 添加用户消息
  const addUserMessage = (content) => {
    messages.value.push({
      id: Date.now(),
      type: 'user',
      content,
      timestamp: new Date()
    })
  }

  // 创建或更新AI消息
  const setAiMessage = (content, isStreaming = false) => {
    const lastMessage = messages.value[messages.value.length - 1]
    
    // 如果最后一条是AI消息且正在流式传输，则更新它
    if (lastMessage && lastMessage.type === 'ai' && lastMessage.isStreaming) {
      lastMessage.content = content
      lastMessage.isStreaming = isStreaming
      if (!isStreaming) {
        lastMessage.timestamp = new Date()
      }
    } else {
      // 否则创建新的AI消息
      messages.value.push({
        id: Date.now(),
        type: 'ai',
        content,
        isStreaming,
        timestamp: isStreaming ? null : new Date()
      })
    }
  }

  // 重置 memoryId（页面刷新时）
  const resetMemoryId = () => {
    localStorage.removeItem('memoryId')
    memoryId.value = getMemoryId()
  }

  return {
    memoryId,
    messages,
    isLoading,
    addUserMessage,
    setAiMessage,
    resetMemoryId,
    setLoading: (loading) => {
      isLoading.value = loading
    }
  }
})

